<template>
  <div>
    <view class="list-content" :style="{ paddingBottom: `${68}px` }">
      <list-empty
        v-if="datalist.length <= 0 || !datalist"
        :style="{ height: listHeight - 68 + 'px', width: '100%' }"
      />
      <view class="left" v-if="isFixed"></view>
      <view
        class="left"
        v-if="leftTab.length > 0"
        :class="[isFixed ? 'fixed' : '']"
        :style="{ top: fixedTopHeight + 'px' }"
      >
        <scroll-view
          scroll-y
          scroll-with-animation
          :style="{ height: `${listHeight}px` }"
          :scroll-top="leftScrollTop"
        >
          <view
            @click="handleCategory(index)"
            :class="[
              'text',
              'nav-item',
              currentIndex === index ? 'active' : '',
            ]"
            v-for="(item, index) in leftTab"
            :id="'classify-' + item.id"
            :key="index"
          >
            <view class="text-content">
              {{ item.name }}
              <view
                class="falg"
                :class="[item.num >= 10 ? 'falgMax' : '']"
                v-if="item.num > 0"
                >{{ item.num }}</view
              >
            </view>
          </view>
        </scroll-view>
      </view>
      <view class="right" v-if="datalist.length > 0">
        <view
          class="class-ify"
          v-for="(item, index) in datalist"
          :key="item.id"
          :style="{
            minHeight:
              index + 1 === datalist.length ? `${listHeight}px` : 'auto',
          }"
        >
          <view class="classify-title" v-if="item.name">{{ item.name }}</view>
          <commodity v-else :good="item" />
          <view v-if="index + 1 == datalist.length" class="no_more"
            >没有更多了</view
          >
          <view style="height: 50px" v-if="index + 1 == datalist.length" />
        </view>
      </view>
    </view>
  </div>
</template>
<script>
import { mixinAuth } from "@/mixin/sp-common/mixin-auth";
import { getCategoryAndGoods } from "@/service/api/sp-store/commodity";
import commodity from "@/components/pageComponents/sp-store/commodity";

import { mapState } from "vuex";
export default {
  components: {
    commodity,
  },
  data() {
    return {
      tabActive: 0,
      tabList: ["点单", "储值"],
      upValue: 0,
      datalist: [],
      nodesTop: [],
      currentIndex: 0,
      contentId: "",
      isFixed: false,
      leftViewHeigt: 0,
      leftScrollTop: 0,
      isOpenTime: true,
      shopInfo: {},
      pubDomainShopId: "",
      couponList: [],
      isShowCouponDown: true,
      showCoupon: false,
      navbarHeight: 0,
      showLoading: true,
      showChange: true,
      isScroll: false,
      isShowWiFi: false,
      shopWiFiList: [],
      isTouch: true,
      leftTab: [],
      pageIndex: 1,
      pageSize: 1000,
      maxPage: 0,
      allData: [],
      listHeadHeight: uni.$u.getPx("100rpx"),
    };
  },
  computed: {
    ...mapState("sp-common/base", ["themeColor"]),
    ...mapState("sp-store/index", [
      "industryType",
      "cartData",
      "lowCompatibility",
    ]),
    ...mapState("sp-common/auth", ["app_token", "isAnonUser"]),
  },
  props: {
    headHeight: {
      require: true,
    },
    listHeight: {
      require: true,
    },
    fixedHeight: {
      require: true,
    },
    fixedTopHeight: {
      require: true,
    },
    pubShopId: {
      require: true,
    },
  },
  watch: {
    app_token(value) {
      if (value) {
        this.initShop();
      }
    },
    pubShopId(value) {
      this.initShop();
    },
    cartData: {
      handler(val) {
        this.setFalgList();
      },
      deep: true,
    },
  },
  created() {
    this.initShop();
  },
  methods: {
    async initShop() {
      let { pubShopId, pubDomainShopId } = uni.$u.$parent.call(
        this,
        "page"
      )._data;
      if (!pubShopId) {
        this.pubShopId = pubDomainShopId;
      }
      if (!pubShopId) return;
      await this.getData();
    },
    // 获取所有商品及相关分类
    getData() {
      let { pubShopId } = this;
      if (this.datalist.length > 0) return;
      getCategoryAndGoods({ pubShopId }).then((res) => {
        let { categoryAndGoods } = res;
        let goods = [],
          leftTab = [],
          sum = 0;
        for (let index = 0; index < categoryAndGoods.length - 1; index++) {
          const ele = categoryAndGoods[index];
          let { name, id, height = 0 } = ele;
          // 60 = title高度   210 = 150h + 30mt + 30pt
          height = 60 + (categoryAndGoods[index]?.goods.length || 0) * 210;
          leftTab.push({ name, id, height });
          goods.push({ name, id });
          goods = [...goods, ...ele.goods];
        }
        this.allData = goods;
        this.leftTab = leftTab;
        this.maxPage = Math.ceil(goods.length / this.pageSize);
        this.$nextTick(() => {
          this.splicData();
          this.setFalgList();
          for (let index = this.leftTab.length - 1; index >= 1; index--) {
            this.leftTab[index].height = this.leftTab[index - 1].height;
          }
          this.leftTab[0].height = 0;
          for (let i = 0; i < this.leftTab.length; i++) {
            sum += this.leftTab[i].height;
            this.leftTab[i].height = uni.$u.getPx(`${sum - 60}rpx`);
          }
          this.leftTab[0].height = 0;
        });
      });
    },
    splicData() {
      let { allData, pageIndex, pageSize, datalist } = this;
      const startIndex = (pageIndex - 1) * pageSize;
      const endIndex = startIndex + pageSize;
      let newData = allData.slice(startIndex, endIndex);
      this.datalist = [...datalist, ...newData];
      this.$nextTick(() => {
        if (datalist.length == allData.length) return;
        this.pageIndex++;
        this.splicData();
      });
    },
    // 分类点击
    handleCategory(index) {
      let { currentIndex } = this;
      if (currentIndex == index) return;
      this.currentIndex = index;
      this.isFixed = true;
      this.isTouch = false;
      uni.pageScrollTo({
        scrollTop: this.leftTab[index].height + this.headHeight,
        duration: 500,
        success: () => {
          setTimeout(() => {
            this.isTouch = true;
          }, 1000);
        },
      });
    },
    // 设置类目的falg
    setFalgList() {
      let {
        cartData: { items },
        leftTab,
      } = this;
      leftTab.forEach((item) => {
        item.num = 0;
      });
      if (items == null) return;
      items.forEach((item) => {
        leftTab.forEach((k) => {
          if (
            item.stockNum >= item.num &&
            item.errorCode !== 55101 &&
            item.errorCode !== 55102
          ) {
            if (item.categoryId === k.id) {
              k.num += item.num;
            }
          }
        });
      });
    },
    pageScroll(e) {
      // uni.$u.throttle(() => {

      this.isFixed = e.scrollTop >= this.fixedHeight ? true : false;
      let top = parseInt(e.scrollTop) - this.headHeight;
      let { leftTab, isTouch } = this;
      if (isTouch) {
        // for (let e = 0; e < leftTab.length; e++) {
        //   console.log(leftTab[e + 1].height)
        //   if (top <= leftTab[e + 1].height && top >= leftTab[e].height) {
        //     // if (this.currentIndex !== datalist[e].id) {
        //     this.currentIndex = e;
        //     //   this.leftScrollTop = leftViewHeigt * (datalist[e].id - 2);
        //     // }
        //   } else if (top >= leftTab[e].height && !leftTab[e + 1].height) {
        //     this.currentIndex = e;
        //     // this.leftScrollTop = leftViewHeigt * (datalist[e - 1].id - 2);
        //   }
        // }
      }
      // }, 300);
    },
  },
};
</script>
<style lang="scss" scoped>
.list-content {
  display: flex;
  .left {
    width: 165rpx;
    font-size: 28rpx;
    font-family: PingFang SC;
    font-weight: 500;
    color: #181818;
    background-color: #f7f7f7;

    .text {
      display: flex;
      align-items: center;
      position: relative;
      min-height: 30rpx;
      padding: 30rpx;
      padding-right: 0 !important;
      .text-content {
        font-size: 30rpx;
        .falg {
          min-width: 26rpx;
          padding: 2rpx;
          height: 26rpx;
          border-radius: 26rpx;
          background: #fe7316;
          font-size: 20rpx;
          font-family: PingFang SC;
          font-weight: bold;
          color: #ffffff;
          position: absolute;
          right: 5rpx;
          top: 10rpx;
          text-align: center;
          line-height: 26rpx;
        }
        .falgMax {
          padding: 2rpx 10rpx;
        }
      }
    }

    .active {
      color: #ffffff;
      background: var(--theme-color);
    }
  }

  .right {
    // flex: 1;
    background: #fff;
    width: calc(100% - 215rpx);
    padding: 0px 25rpx 50px;
    .class-ify {
      padding-top: 30rpx;
      .classify-title {
        font-size: 28rpx;
        font-family: PingFang SC;
        font-weight: 500;
        color: #131313;
        height: 30rpx;
        // margin-top: 30rpx;
        // height: 55rpx;
        // line-height: 55px;
      }
    }
  }
}
.no_more {
  padding: 20rpx 0;
  text-align: center;
  font-size: 27rpx;
  color: #888888;
}

// }
.fixed {
  width: 100%;
  left: 0;
  z-index: 111;
  position: fixed;
}
</style>
